package com.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.base.persistence.Page;
import com.github.pagehelper.PageHelper;
import com.system.mapper.SysMenuMapper;
import com.system.mapper.SysRoleMapper;
import com.system.service.ISysRoleService;
import com.system.vo.SysMenuVO;
import com.system.vo.SysRoleVO;

@Service("roleService")
public class SysRoleServiceImpl implements ISysRoleService {

	@Resource
	private SysRoleMapper roleMapper;
	
    @Resource
	private SysMenuMapper sysCodeMenusMapper;
    
	@Override
	public List<SysRoleVO> getRoleListBypage(Page<SysRoleVO> page, SysRoleVO vo) {
		int start = page.getPage();
		int pageSize = page.getRows();
		PageHelper.startPage(start,pageSize,true);  //第一页 每页显示10条
		List<SysRoleVO> list =roleMapper.getAllRole(vo);
		page.loadData(list);
		return page.getList();
	}

	@Override
	public List<SysRoleVO> getRolesByType(String roleType) {
		return null;
	}
	
	@Override
	public List<SysMenuVO> findPermissionsByRoleId(String roleID) {
		List<String>menuIds=roleMapper.findPermissions(roleID);
		if(menuIds!=null&&menuIds.size()>0){
		  return sysCodeMenusMapper.findMenusByMenuIds(menuIds);
		}
		
		return null;
	}
	
	@Override
	public void deleteRoles(List<String> roleIds) throws Exception {
		roleMapper.deleteRolesAndMenus(roleIds);
		roleMapper.deleteRolesAndStaffs(roleIds);
		roleMapper.deleteRoles(roleIds);
	}
	
	@Override
	public void updateRole(SysRoleVO role) throws Exception {
		roleMapper.update(role);
		
	}


	//绑定角色与资源的联系
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createRoleAndMenus(String roleId, List<String> ids) throws Exception {
		List<String>roleIds=new ArrayList<String>();
		roleIds.add(roleId);
		roleMapper.deleteRolesAndMenus(roleIds);
		for (String menuId : ids) {
			roleMapper.saveRoleandMenu(roleId, menuId);
		}
	}
	
	@Override
	public void save(SysRoleVO role) throws Exception {
		roleMapper.save(role);
	}
	
	@Override
	public List<SysRoleVO> findSysRoleVOsBymap(Page<SysRoleVO> page, String roleGroupId,
                                               String roleName) {
		int start=page.getPage();
		int limit=page.getRows();
		PageHelper.startPage(start,limit,true);
		List<SysRoleVO>list=roleMapper.findSysRoleVOsBymap(roleGroupId,
				roleName);
		page.loadData(list);
		return page.getList();
	}

	@Override
	public SysRoleVO findRoleById(String roleId) {
		return roleMapper.findRoleById(roleId);
	}

}
